package czk.concrent.enjoyModelWithNotLock.lockCas;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * cas实现锁的原理，但是不要运用于生产实践
 * @Author:ChenZhangKun
 * @Date: 2020/6/16 22:21
 */
public class LockCas {
    private  AtomicInteger atomicInteger=new AtomicInteger(0);
    // 加锁
    public  void lock(){
        while (true){
            if (atomicInteger.compareAndSet(0,1)){
                break;
            }
        }
    }
    // 释放锁
    public  void unlock(){
        atomicInteger.set(0);
    }

    public static void main(String[] args) {
        LockCas lock=new LockCas();
        new Thread(()->{
            try {
                System.out.println("begin");
                lock.lock();
                try {
                    System.out.println("阻塞中");
                    Thread.sleep(2*1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }finally {
                lock.unlock();
            }

        }).start();
        try {
            Thread.sleep(1*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            try {
                System.out.println("begin");
                // 该线程会陷入死循环，知道被重新设置为0
                lock.lock();
                System.out.println("阻塞");
            }finally {
                lock.unlock();
            }
        }).start();
    }
}
